package hng.controller;


import hng.component.RedisComponent;
import hng.constants.Constants;
import hng.dto.RegisterDTO;
import hng.dto.ResetPasswordDTO;
import hng.dto.UserDTO;
import hng.enums.CaptchaEnum;
import hng.exception.BizException;
import hng.model.UserDO;
import hng.service.UserService;
import hng.util.CommonUtil;
import hng.util.CreateImageCode;
import hng.util.JsonData;
import hng.vo.LoginVO;
import hng.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 告白
 * @since 2024-06-27
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired(required = false)
    private UserService userService;

    @Autowired(required = false)
    private RedisComponent redisComponent;

    /**
     * 获取图形验证码
     */
    @GetMapping("/get-captcha")
    public void checkCode(HttpServletResponse response,
                          HttpServletRequest request) throws IOException {
        CreateImageCode vCode = new CreateImageCode(130, 38, 5, 10);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String code = vCode.getCode();
        HttpSession session = request.getSession();
        String id = session.getId();
        log.info("id: {}", id);
        String key = getCaptchaKey(request);
        redisComponent.saveCaptcha(key, code);
        vCode.write(response.getOutputStream());
    }

    /**
     * 发送短信验证码
     */
    @GetMapping("/send-phone-code")
    public JsonData sendPhoneCode(HttpServletRequest request,
                                  @RequestParam String phone,
                                  @RequestParam String captcha) {
        String key = getCaptchaKey(request);
        try {
            String code = (String) redisComponent.get(key);
            log.info("图形验证码: {}", code);
            if (!captcha.equalsIgnoreCase(code)) {
                throw new BizException("图形验证码错误");
            }
            userService.sendPhoneCode(phone);
            return JsonData.buildSuccess();
        } finally {
            redisComponent.delKey(key);
        }
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public JsonData register(@RequestBody RegisterDTO registerDTO) {
        userService.register(registerDTO);
        return JsonData.buildSuccess();
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public JsonData login(HttpServletRequest request, @RequestBody RegisterDTO registerDTO) {
        String key = getCaptchaKey (request);
        try {
            String code = (String) redisComponent.get(key);
            log.info("图形验证码: {}", code);
            if (!registerDTO.getCode().equalsIgnoreCase(code)) {
                throw new BizException("图形验证码错误");
            }
            LoginVO loginVO = userService.login(registerDTO);
            return JsonData.buildSuccess(loginVO);
        } finally {
            redisComponent.delKey(key);
        }
    }


    /**
     * 获取个人信息
     */
    @GetMapping("info")
    public JsonData info() {
        UserVO userVO = userService.info();
        return JsonData.buildSuccess(userVO);
    }

    /**
     * 修改个人信息
     */
    @PostMapping("/update-info")
    public JsonData updateInfo(@RequestBody UserDTO userDTO) {
        UserVO userVO = userService.updateInfo(userDTO);
        return JsonData.buildSuccess(userVO);
    }

    /**
     * 修改密码
     */
    @PostMapping("/update-password")
    public JsonData updatePassword(@RequestBody ResetPasswordDTO resetPasswordDTO) {
        userService.updatePassword(resetPasswordDTO);
        return JsonData.buildSuccess();
    }

    /**
     * TODO
     * 找回密码
     */

    /**
     * 获取验证码的key
     */
    private String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = String.format(Constants.REDIS_KEY_CAPTCHA, CommonUtil.MD5(ip + userAgent));
        log.info("ip={}",ip);
        log.info("userAgent={}",userAgent);
        log.info("key={}",key);
        return key;
    }

}

